<?php

namespace app\admin\controller\calculation;

use app\common\controller\Backend;
use app\admin\model\SalaryCalculationTemplateItem;
use think\Db;
/**
 * 工资计算模板管理管理
 *
 * @icon fa fa-circle-o
 */
class SalaryCalculationTemplate extends Backend
{

    /**
     * SalaryCalculationTemplate模型对象
     * @var \app\admin\model\SalaryCalculationTemplate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SalaryCalculationTemplate;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','template_name','staff_type','create_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    if($params['copy_type'] == 1){
                        $params['id'] = 0;
                    }
                    $arr = array(
                        'template_name' => $params['templateName'],
                        'staff_type' => $params['staffType'],
                    );
                    if(empty($params['id'])){
                        $res = $this->model->save($arr);
                        $template_id = $this->model->id;
                    }else{
                        $temInfo = $this->model->get($params['id']);
                        if(empty($temInfo))$this->error('获取内容失败');
                        $res = $this->model->where('id',$params['id'])->update($arr);
                        $template_id = $params['id'];
                        $del_res = SalaryCalculationTemplateItem::where('template_id',$template_id)->delete();
                        if(!$del_res)exception('操作失败D');
                    }
                    if($res === false)exception('操作失败');
                    $item_arr = [];
                    foreach ($params['calculationForms'] as $v){
                        array_push($item_arr,array(
                            'template_id' => $template_id,
                            'item_name'=> $v['itemName'],
                            'item_type'=> $v['itemType'],
                            'formula_text'=> $v['calculatedFormula'],
                            'formula'=> json_encode($v['calculatedFormulaValue']),
                        ));
                    }
                    $item_res = (new SalaryCalculationTemplateItem())->saveAll($item_arr);
                    if(!$item_res)exception('操作失败I');
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('id',0);
        $this->assignconfig('copy_type',0);
        $this->view->assign('copy_type',0);
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids=null)
    {
        if ($this->request->isPost()) {
           $id = $this->request->post('id');
           $temInfo = $this->model->get($id);
           if(empty($temInfo))$this->error('获取内容失败');
           $temItemInfo = SalaryCalculationTemplateItem::where(['template_id'=>$id])->select();
           $data = [];
           foreach ($temItemInfo as $k=>$v){
               $data[$k]['itemName'] = $v['item_name'];
               $data[$k]['itemType'] = $v['item_type'];
               $formula = json_decode($v['formula'],true);
               $data[$k]['calculatedFormulaValue'] = $formula;
               $data[$k]['calculatedFormula'] = $v['formula_text'];
           }
            $temInfo['calculationForms'] = $data;
            $this->success('ok','',$temInfo);
        }
        $copy_type = $this->request->get('type',0);
        $this->assignconfig('id',$ids);
        $this->assignconfig('copy_type',$copy_type);
        $this->view->assign('copy_type',$copy_type);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        if ($ids) {
            Db::startTrans();
            try {
                $temRes = $this->model->whereIn('id',$ids )->delete();
                $temItemRes = SalaryCalculationTemplateItem::where(['template_id'=>$ids])->delete();
                if(!$temRes || !$temItemRes)exception('删除失败');
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
